package com.qf.huigou.controller;

import com.qf.huigou.Service.UserService;
import com.qf.huigou.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

@Controller
public class UserController {

    @Resource
    UserService userService;

    // 上传图片目录路径
    public static final String UPLOAD_DIR = "D:\\apache-tomcat-7.0.53\\webapps\\assets\\img\\";

    @RequestMapping("signin")
    public String loginMapper(){
        return "login";
    }

    @RequestMapping("register")
    public String registMapper(){
        return "regist";
    }

    /**
     * 登录功能
     * @param phonenumber
     * @param password
     * @return
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(HttpServletRequest req, HttpServletResponse resp,String phonenumber, String password,String code){
        String cd = (String) req.getSession().getAttribute("code");
        if(code.equalsIgnoreCase(cd)){
            User user = userService.login(phonenumber, password);
            if(user!=null){
                return "redirect:selectByPage";
            }else{
                req.setAttribute("msg","登录失败");
                return "login";
            }
        }else{
            req.setAttribute("msg","验证码错误");
            return "login";
        }
    }

    /**
     * 画验证码
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String[] letters = {"a","b","c","e","d","f","g","h","i","j","k","l","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
                ,"0","1","2","3","4","5","6","7","8","9"};
        int width = 160,height=30;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics p = image.getGraphics();
        p.setColor(getRandomColor());
        p.fillRect(0, 0, width, height);
        Random ran = new Random();
        for(int i=0 ; i<10;i++) {
            p.setColor(getRandomColor());
            p.drawLine(ran.nextInt(width),ran.nextInt(height), ran.nextInt(width), ran.nextInt(height));
        }
        int r = ran.nextInt(3) + 2;
        for (int i = 0; i < 10; i++) {
            p.setColor(getRandomColor());
            p.drawOval(ran.nextInt(width), ran.nextInt(height), r, r);
        }
        int c = 5,space=5;
        int zw = (width-(c+1)*space)/c;
        String code="";
        for (int i = 0; i < c; i++) {
            int index = ran.nextInt(letters.length);
            String letter = letters[index];
            p.setColor(getRandomColor());
            p.setFont(new Font("楷体",Font.BOLD,23));
            p.drawString(letter, space+(space+zw)*i, height*4/5);
            code = code + letter;
        }
        System.out.println(code);
        request.getSession().setAttribute("code", code);
        ImageIO.write(image, "PNG", response.getOutputStream());
    }

    /**
     * 自定义随机颜色
     * @return
     */
    public Color getRandomColor() {
        Random ran = new Random();
        int r = ran.nextInt(256);
        int g = ran.nextInt(256);
        int b = ran.nextInt(256);
        return new Color(r, g, b);
    }

    /**
     * 注册功能
     * @param user
     * @param headImg
     * @param model
     * @return
     */
    @RequestMapping(value = "regist",method = RequestMethod.POST)
    public String regist(User user, @RequestParam(value = "headImg",required = false) CommonsMultipartFile headImg, Model model){
        if(StringUtils.isNotBlank(headImg.getOriginalFilename())){
            String name = headImg.getOriginalFilename();
            String suffix = name.substring(name.lastIndexOf("."));
            String filename = System.currentTimeMillis() + suffix;
            File destFile = new File(UPLOAD_DIR+filename);
            try {
                headImg.transferTo(destFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            user.setImg(filename);
        }else{
            user.setImg(null);
        }
        int regist = userService.regist(user);
        if(regist == 1){
            model.addAttribute("msg","注册成功");
            return "login";
        }else{
            model.addAttribute("msg","注册失败");
            return "login";
        }
    }

    @RequestMapping("selectByNumber")
    public void selectByNumber(String phonenumber,PrintWriter pw){
        User user = userService.selectByNumber(phonenumber);
        if(user!=null){
            pw.print(true);
        }else{
            pw.print(false);
        }
    }

}
